import React, { Component } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import moment from 'utils/moment'
import delete2 from 'images/index/crop/delete.png'
import { Table, Button, Select, Input } from 'antd'
import { connect } from 'react-redux'
import { updateSchedule, delSchedule } from '_redux/actions/cropPlan'
import { DebounceInput } from 'react-debounce-input'
import { toast } from 'react-toastify'
const Option = Select.Option

const dictionary = {
  'urea': '0',
  'ammonium': '1',
  'diammonium': '2',
  'kso4': '3',
  'znso4': '4',
  'boron': '5',
  'h2kp': '6',
  'canola': '7',
  'kcl': '8',
  'nacterial': '9',
  'organic': '10',
  'other': '11',
  'maxed': '12',
  'compound': '13'
}


function calcDosage(contrast, type, start = 0) {
  return contrast.filter(c => c.category === type)
    .map(c => Number(c.dosage)).reduce((a, b) => a + b, start)
}

function isShow(contrast, type) {
  return contrast.filter(c => c.category === dictionary[type]).length === 0
}
const calcAfterFilter = function (arr, type, filter, start = 0) {
  return arr.map(a => Number(filter(a[type] || 0))).reduce((a, b) => a + b, start)
}
class Delivery extends Component {
  constructor() {
    super()
    this.state = {
      data: [],
      total: []
    }
  }
  workTypeChange = (key, value) => {
    const { cropPlan: { schedule } } = this.props
    for (let con of schedule) {
      if (con.key === key) {
        con.workType = value
        break
      }
    }
    this.props.updateSchedule(schedule)
  }
  change = (key, e) => {
    const { name, value } = e.target
    const { cropPlan: { schedule, unit } } = this.props
    if (unit === 2) {
      toast.error('百分比情况下，不可输入，请切换到其他单位')
      return
    }
    for (let con of schedule) {
      if (con.key === key) {
        con[name] =
          unit === 0 ? Number(value) : Number(value) / 15
        break
      }
    }
    this.props.updateSchedule(schedule)
  }
  change2 = (key, e) => {
    const { name, value } = e.target
    const { cropPlan: { schedule, unit } } = this.props
    if (unit === 2) {
      toast.error('百分比情况下，不可输入，请切换到其他单位')
      return
    }
    for (let con of schedule) {
      if (con.key === key) {
        con[name] = value
        break
      }
    }
    this.props.updateSchedule(schedule)
  }
  dateChange = (key, e) => {
    const { cropPlan: { schedule, details: { sowingDate } } } = this.props
    const { name, value } = e.target
    for (let con of schedule) {
      if (con.key === key) {
        con[name] = value
        con.executionDate = moment(sowingDate).add(value, 'days').format('YYYY-MM-DD')
        break
      }
    }
    this.props.updateSchedule(schedule)
  }
  format2 = (value) => {
    if (typeof value === 'undefined' || isNaN(value)) {
      return '0'
    }
    const { cropPlan: { unit } } = this.props
    if (unit === 1) {
      return (Number((Number(value) * 15).toFixed())).toString()
    } else if (unit === 0) {
      return (Number(Number(value).toFixed(1))).toString()
    }
  }
  formatTotal = (type) => {
    const { cropPlan: { schedule } } = this.props
    return this.format2(calcAfterFilter(schedule, type, v => v))
  }
  addSchedule = () => {
    const { cropPlan: { schedule, contrast } } = this.props
    schedule.push({
      key: schedule.length,
      executionDate: undefined,
      workType: undefined,
      urea: isShow(contrast, 'urea') ? undefined : 0,
      ammonium: isShow(contrast, 'ammonium') ? undefined : 0,
      diammonium: isShow(contrast, 'diammonium') ? undefined : 0,
      kso4: isShow(contrast, 'kso4') ? undefined : 0,
      znso4: isShow(contrast, 'znso4') ? undefined : 0,
      boron: isShow(contrast, 'boron') ? undefined : 0,
      h2kp: isShow(contrast, 'h2kp') ? undefined : 0,
      canola: isShow(contrast, 'canola') ? undefined : 0,
      kcl: isShow(contrast, 'kcl') ? undefined : 0,
      nacterial: isShow(contrast, 'nacterial') ? undefined : 0,
      organic: isShow(contrast, 'organic') ? undefined : 0,
      other: isShow(contrast, 'other') ? undefined : 0,
      maxed: isShow(contrast, 'maxed') ? undefined : 0,
      compound: isShow(contrast, 'compound') ? undefined : 0,
      afterSwoDays: undefined,
      dripIrrigationTime: undefined,
      dripIrrigationQuantity: undefined,
      describe: ''
    })
    this.props.updateSchedule(schedule)
  }
  isStandard = (type) => {
    const { cropPlan: { schedule, contrast } } = this.props
    return this.format2(calcAfterFilter(schedule, type, v => v))
      !== this.format2(calcDosage(contrast, dictionary[type]))
  }
  deleteById = (key) => {
    const { cropPlan: { schedule } } = this.props
    if (key.toString().length === 32) {
      this.props.delSchedule(key)
    }
    this.props.updateSchedule(schedule.filter(d => d.key !== key))
  }
  generateRender = (type) => {
    const { cropPlan: { contrast }} = this.props
    return (value, row, index) => {
      if (row.key === -1) {
        const obj = {
          children: value,
          props: {
            className: classNames({
              unStandard: this.isStandard(type),
              hidden: isShow(contrast, type)
            })
          },
        }
        return obj
      }
      return <DebounceInput
        minLength={0}
        debounceTimeout={500 * 2}
        value={this.format2(value)}
        name={type}
        onChange={this.change.bind(this, row.key)} />
    }
  }

  render() {
    const { cropPlan: { schedule, contrast } } = this.props
    return (
      <div className='delivery'>
        <Table
          columns={[{
            title: '顺序',
            dataIndex: 'order',
            className: 'noBottomBorder noRightBorder noLeftBorder',
            render: (value, row, index) => {
              if (row.key === -1) {
                return ''
              }
              return index + 1
            }
          }, {
            title: '执行日期',
            dataIndex: 'executionDate',
            className: 'noBottomBorder',
            render: (value, row, index) => {
              if (row.key === -1) {
                return ''
              }
              if (!value) {
                return ''
              }
              return moment(value).format('MM/DD/YYYY')
            }
          }, {
            title: '作业（*）',
            dataIndex: 'workType',
            render: (value, row, index) => {
              if (row.key === -1) {
                return '合计'
              }
              return <Select defaultValue="0" value={value} name='workType' size={'small'} onChange={this.workTypeChange.bind(this, row.key)}>
                <Option value="0">春底肥</Option>
                <Option value="1">秋底肥</Option>
                <Option value="2">种肥</Option>
                <Option value="3">追肥</Option>
                <Option value="4">水+肥</Option>
                <Option value="5">叶面肥</Option>
                <Option value="6">出苗水</Option>
                <Option value="7">芸苔素</Option>
                <Option value="8">清水</Option>
              </Select>
            }
          }, {
            title: '尿素',
            dataIndex: 'urea',
            className: isShow(contrast, 'urea') ? 'hidden' : '',
            render: this.generateRender('urea')
          }, {
            title: '一铵',
            dataIndex: 'ammonium',
            className: isShow(contrast, 'ammonium') ? 'hidden' : '',
            render: this.generateRender('ammonium')
          }, {
            title: '二铵',
            dataIndex: 'diammonium',
            className: isShow(contrast, 'diammonium') ? 'hidden' : '',
            render: this.generateRender('diammonium')
          }, {
            title: '硫酸钾',
            dataIndex: 'kso4',
            className: isShow(contrast, 'kso4') ? 'hidden' : '',
            render: this.generateRender('kso4')
          }, {
            title: '硫酸锌',
            dataIndex: 'znso4', 
            className: isShow(contrast, 'znso4') ? 'hidden' : '',
            render: this.generateRender('znso4')
          }, {
            title: '硼肥',
            dataIndex: 'boron', 
            className: isShow(contrast, 'boron') ? 'hidden' : '',
            render: this.generateRender('boron')
          }, {
            title: '磷酸二氢钾',
            dataIndex: 'h2kp', 
            className: isShow(contrast, 'h2kp') ? 'hidden' : '',
            render: this.generateRender('h2kp')
          }, {
            title: '芸苔素',
            dataIndex: 'canola', 
            className: isShow(contrast, 'canola') ? 'hidden' : '',
            render: this.generateRender('canola')
          }, {
            title: '氯化钾',
            dataIndex: 'kcl', 
            className: isShow(contrast, 'kcl') ? 'hidden' : '',
            render: this.generateRender('kcl')
          }, {
            title: '菌肥',
            dataIndex: 'nacterial',
            className: isShow(contrast, 'nacterial') ? 'hidden' : '',
            render: this.generateRender('nacterial')
          }, {
            title: '有机肥',
            dataIndex: 'organic',
            className: isShow(contrast, 'organic') ? 'hidden' : '',
            render: this.generateRender('organic')
          }, {
            title: '掺混肥',
            dataIndex: 'maxed',
            className: isShow(contrast, 'maxed') ? 'hidden' : '',
            render: this.generateRender('maxed')
          }, {
            title: '复合肥',
            dataIndex: 'compound',
            className: isShow(contrast, 'compound') ? 'hidden' : '',
            render: this.generateRender('compound')
          }, {
            title: '其他',
            dataIndex: 'other',
            className: isShow(contrast, 'other') ? 'hidden' : '',
            render: this.generateRender('other')
          }, {
            title: '播后天数（*）',
            dataIndex: 'afterSwoDays',
            render: (value, row, index) => {
              if (row.key === -1) {
                return ''
              }
              return <Input size="small"
                value={value}
                name='afterSwoDays'
                onChange={this.dateChange.bind(this, row.key)} />
            }
          }, {
            title: '滴水时间（h）',
            dataIndex: 'dripIrrigationTime',
            render: (value, row, index) => {
              if (row.key === -1) {
                return ''
              }
              return <Input
                size="small"
                value={value}
                name='dripIrrigationTime'
                onChange={this.change2.bind(this, row.key)} />
            }
          }, {
            title: '滴灌量（m3/亩）',
            dataIndex: 'dripIrrigationQuantity',
            render: (value, row, index) => {
              if (row.key === -1) {
                return ''
              }
              return <Input
                size="small"
                value={value}
                name='dripIrrigationQuantity'
                onChange={this.change2.bind(this, row.key)} />
            }
          }, {
            title: '说明',
            dataIndex: 'describe',
            render: (value, row, index) => {
              if (row.key === -1) {
                return ''
              }
              return <Input
                size="small"
                value={value}
                name='describe'
                onChange={this.change2.bind(this, row.key)} />
            }
          }, {
            title: '',
            key: 'operation',
            className: 'operation-hover',
            render: (text, row, index) => {
              if (row.key === -1) {
                return ''
              }
              return <div>
                <img src={delete2} title='删除' alt="" onClick={this.deleteById.bind(this, row.key)} />
              </div>
            }
          }]}
          dataSource={[...schedule, {
            key: -1,
            urea: this.formatTotal('urea'),
            ammonium: this.formatTotal('ammonium'),
            diammonium: this.formatTotal('diammonium'),
            kso4: this.formatTotal('kso4'),
            znso4: this.formatTotal('znso4'),
            boron: this.formatTotal('boron'),
            h2kp: this.formatTotal('h2kp'),
            canola: this.formatTotal('canola'),
            kcl: this.formatTotal('kcl'),
            nacterial: this.formatTotal('nacterial'),
            organic: this.formatTotal('organic'),
            maxed: this.formatTotal('maxed'),
            compound: this.formatTotal('compound'),
            other: this.formatTotal('other'),
          }]}
          locale={{ emptyText: '无数据' }}
          bordered
          size={'small'}
          title={() => '执行计划'}
          footer={undefined}
          pagination={false}
        />
        <div className='addAction'>
          <Button onClick={this.addSchedule} className='button'>添加日程</Button>
        </div>
      </div>
    )

  }
}
Delivery.propTypes = {
  cropPlan: PropTypes.object,
  updateSchedule: PropTypes.func,
  delSchedule: PropTypes.func,
}
export default connect(({ cropPlan }) => ({ cropPlan }), (dispatch) => ({
  updateSchedule: (schedule) => dispatch(updateSchedule(schedule)),
  delSchedule: (key) => dispatch(delSchedule(key))
}))(Delivery)